require 'resolv'

class User < ActiveRecord::Base
  belongs_to :user_group
  belongs_to :domain
  has_one :invalid_user

  validates :email, presence: true,
                    uniqueness: true,
                    format: /\A[^@\s]+@[^@\s]+\z/
  validate :email_domain_should_be_real

  before_save :normalize_email
  before_save :set_domain
  before_create :set_user_group

  def name_or_email
    name or email
  end

  def name_and_email
    %Q("#{name}" <#{email}>)
  end

  def self.search_by_email_or_domain_name(email_or_domain_name)
    if email_or_domain_name['@']
      @users = User.where(email: email_or_domain_name)
    else
      domain = Domain.where(name: email_or_domain_name).take
      @users = domain ? domain.users : User.none
    end
  end

  private
  def email_domain_should_be_real
    domain_name = email.split('@').last
    begin
      raise '' unless Resolv::DNS.new.getresource(domain_name, Resolv::DNS::Resource::IN::MX)
    rescue
      errors.add :email, 'Domain does not exist.'
    end
  end

  def normalize_email
    self.email.downcase!
  end

  def set_domain
    domain_name = email.split('@').last.strip
    self.domain = Domain.find_or_create_by(name: domain_name)
  end

  def set_user_group
    self.user_group ||= UserGroup.find_by(name: 'Default')
  end
end
